/**
 * Filename: UpLoadService.java
 *
 * @author Firefly
 * @contact postfirefly@163.com
 * @time 2016/3/17 16:06
 */
package com.github.postsanf.yinian.service;

import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;

import com.github.postsanf.yinian.BaseIntentService;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.YNBackUp;
import com.github.postsanf.yinian.bean.YNResponse;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNUpTokenResponse;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCancellationSignal;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

public class BackUpService extends BaseIntentService {
    private UploadManager mUpManager;
    private boolean isFirst = true;     // 首次获取Token
    private Timer timer;
    private String fileKey;
    private int total = 0;
    private String localurls;
    private String localtimes;
    private int userid;
    boolean is3GType = false;
    boolean bbisCancel = false;
    private Thread mThread;
    private static List<String> listBackup = new ArrayList<>();

    public BackUpService() {
        super("BackUpService");
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    String path = (String) msg.obj;
                    ++total;
                    Log.i("xjs", "total==>" + total);
                    ConnectivityManager mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    NetworkInfo networkInfo = mConnectivityManager.getActiveNetworkInfo();
                    if (networkInfo != null && networkInfo.isAvailable()) {
                        if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                            //WiFi网络
                            Log.i("xjs", "wifiiii");
                            is3GType = true;
                        } else if (networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                            //3g网络
                            Log.i("xjs", "3ggg网络");
                            if (is3GType) {
                                Log.i("xjs", "停止备份");
                                bbisCancel = true;
                                for (int i = 0; i < listBackup.size(); i++) {
                                    listBackup.remove(i);
                                }
                                listBackup.clear();
                                stopSelf();
                            }
                            is3GType = false;
                        }
                    }
                    break;
                case 4:
                    YNBackUp ynBackUp = (YNBackUp) msg.obj;
                    List<String> uploadkey = ynBackUp.getUploadkey();
                    List<String> uploadpath = ynBackUp.getUploadpath();
                    List<String> uploadtime = ynBackUp.getUploadtime();
                    String keys = null;
                    for (int i = 0; i < uploadkey.size(); i++) {
                        String strings = uploadkey.get(i);
                        if (keys == null) {
                            keys = strings;
                        } else {
                            keys = keys + "," + strings;
                        }
                    }
                    String paths = null;
                    for (int j = 0; j < uploadpath.size(); j++) {
                        String strings = uploadpath.get(j);
                        if (paths == null) {
                            paths = strings;
                        } else {
                            paths = paths + "," + strings;
                        }
                    }
                    String times = null;
                    for (int k = 0; k < uploadtime.size(); k++) {
                        String stringst = uploadtime.get(k);
                        if (times == null) {
                            times = stringst;
                        } else {
                            times = times + "," + stringst;
                        }
                    }
                    Log.i("xjs", "keys=" + keys);
                    Log.i("xjs", "paths=" + paths);
                    Log.i("xjs", "times=" + times);
                    UploadToBackUp(keys, paths, times);
                    break;
            }
        }
    };

    @Override
    public void onCreate() {
        super.onCreate();
        mUpManager = application.getUploadManager();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            switch (action) {
                case ACTIONs.actionBackupPhoto:
                    localurls = intent.getStringExtra(ACTIONs.aUrl);
                    localtimes = intent.getStringExtra(ACTIONs.aTime);
                    userid = intent.getIntExtra(ACTIONs.aUserId, 0);
                    if (localurls.contains(",")) {
                        String[] picarrs = localurls.split(",");
                        for (int i = 0; i < picarrs.length; i++) {
                            listBackup.add(picarrs[i]);
                        }
                    } else {
                        listBackup.add(localurls);
                    }
                    if (listBackup.size() > 0 && userid != 0) {
                        mThread = new Thread() {
                            @Override
                            public void run() {
                                super.run();
                                getToken();
                            }
                        };
                        mThread.start();
                    }
                    break;
                case ACTIONs.actionCancelBackupPhoto:
                    Log.i("xjs", "actionCancelBackupPhoto");
                    bbisCancel = true;
                    for (int i = 0; i < listBackup.size(); i++) {
                        listBackup.remove(i);
                    }
                    listBackup.clear();
                    stopSelf();
                    break;
            }
        }
    }


    private void getToken() {
        if (isFirst) {
            doTokenPrepare();
            //如果token无效2秒后自动上传
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            getToken();
            return;
        }
        uploadToqiniu();
    }

    List<String> uploadpath = new ArrayList<>();
    List<String> uploadkey = new ArrayList<>();
    List<String> uploadtime = new ArrayList<>();

    private String uploadToqiniu() {
        final String path = listBackup.get(0);
        final File uploadFile = new File(path);
        String prefix = path.substring(path.lastIndexOf(".") + 1);
        // 为图片重命名
        String imgName = UUID.randomUUID().toString() + "." + prefix;
        mUpManager.put(uploadFile, imgName, application.getUpToken(),
                new UpCompletionHandler() {
                    @Override
                    public void complete(String key, ResponseInfo respInfo, JSONObject jsonData) {
                        if (respInfo.isOK()) {
                            try {
                                fileKey = jsonData.getString("key");
                                uploadkey.add(fileKey);
                                Message message = new Message();
                                message.what = 1;
                                message.obj = path;
                                handler.sendMessage(message);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            showLog("----------------------------七牛云上传图片失败---------------------------------");
                            fileKey = null;
                        }
                        uploadpath.add(path);
                        uploadtime.add(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(new File(path).lastModified())));
                        listBackup.remove(path);
                        if (listBackup.size() == 0) {
                            //由于莫名其妙的图片上传完毕而100%进度没有存入本地所以延时发送消息2
//                            handler.postDelayed(new Runnable() {
//                                @Override
//                                public void run() {
//                                    handler.sendEmptyMessage(3);
//                                }
//                            }, 20);
                            if (uploadpath.size() <= 5) {
                                YNBackUp ynBackUp = new YNBackUp();
                                ynBackUp.getUploadkey().addAll(uploadkey);
                                ynBackUp.getUploadpath().addAll(uploadpath);
                                ynBackUp.getUploadtime().addAll(uploadtime);
                                Message message = new Message();
                                message.what = 4;
                                message.obj = ynBackUp;
                                handler.sendMessage(message);
                                uploadkey.clear();
                                uploadpath.clear();
                                uploadtime.clear();
                            }
                        } else {
                            if (uploadpath.size() % 5 == 0) {
                                YNBackUp ynBackUp = new YNBackUp();
                                ynBackUp.getUploadkey().addAll(uploadkey);
                                ynBackUp.getUploadpath().addAll(uploadpath);
                                ynBackUp.getUploadtime().addAll(uploadtime);
                                Message message = new Message();
                                message.what = 4;
                                message.obj = ynBackUp;
                                handler.sendMessage(message);
                                uploadkey.clear();
                                uploadpath.clear();
                                uploadtime.clear();
                            }
                            uploadToqiniu();
                        }
                    }
                }, new UploadOptions(null, null, false,
                        new UpProgressHandler() {
                            @Override
                            public void progress(String key, double percent) {

                            }
                        }, new UpCancellationSignal() {
                    @Override
                    public boolean isCancelled() {
                        return bbisCancel;
                    }
                }));
        return fileKey;
    }


    private void UploadToBackUp(String url, String localpaths, String localtimes) {
        String urlsto = getString(R.string.SLIVER_URL) + "SaveUserPhoto";
        LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
        Log.i("xjs", "application.getCurID()==>" + userid);
        mParam.put(CommonConstants.YNS_USER_ID, String.valueOf(userid));
        mParam.put("url", url);
        mParam.put("key", localpaths);
        mParam.put("time", localtimes);
        StringRequest req = new StringRequest(urlsto)
                .setMethod(HttpMethods.Post)
                .setParamMap(mParam)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNResponse res = gson.fromJson(s, YNResponse.class);
                        if (TextUtils.equals(res.getMsg(), "success")) {
                            Log.i("xjs", "UploadToBackUp=" + "isSuccess");
                        } else {
                            Log.i("xjs", "UploadToYiNian=" + "fail");
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }


    // 主动获取Token  间隔30分钟
    private void doTokenPrepare() {
        if (timer == null) {
            timer = new Timer();
        }
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                // getToken();
                getPrivateSpaceUploadToken();
            }
        }, 300, 30 * 60 * 1000);
    }

    private void getPrivateSpaceUploadToken() {
        StringRequest req = new StringRequest(getString(R.string.BASE_URL) + getString(R.string.ynGetPrivateSpaceUploadToken))
                .setMethod(HttpMethods.Post)
                .setHttpListener(new HttpListener<String>(true, false, true) {
                    @Override
                    public void onSuccess(String s, Response<String> response) {
                        YNUpTokenResponse resToken = gson.fromJson(s, YNUpTokenResponse.class);
                        if (ReqUtils.isSuccess(resToken.getCode())) {
                            application.setUpToken(resToken.getData().get(0).getToken());
                            if (isFirst) {
                                isFirst = false;
                            }
                            handler.sendEmptyMessage(0);
                        } else {
                            showToast(resToken.getMsg());
                        }
                    }

                    @Override
                    public void onFailure(HttpException e, Response<String> response) {
                        //  showToast(CommonConstants.YN_NET_LINK);
                    }
                });
        liteHttp.executeAsync(req);
    }

}